package com.yunkaweilai.android.activity.operation.consumption.shops;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.adapter.multilayout.ShopAdapterItem;
import com.yunkaweilai.android.adapter.multilayout.TimeAdapterItem;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.UpdateGoodsNumInterfaces;
import com.yunkaweilai.android.interfaces.adapter.ShopItemInterface;
import com.yunkaweilai.android.interfaces.adapter.TimeItemInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.shop.SearchShopModel;
import com.yunkaweilai.android.model.shop.ShopSkuInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.zxing.camera.CameraManager;
import com.yunkaweilai.android.utils.zxing.decoding.CaptureActivityHandler;
import com.yunkaweilai.android.utils.zxing.decoding.InactivityTimer;
import com.yunkaweilai.android.utils.zxing.view.ViewfinderView;
import com.yunkaweilai.android.view.dialog.UpdateGoodsNumDialogForSearch;
import com.zhy.adapter.abslistview.MultiItemTypeAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 扫码消费
 * Created by Administrator on 2017/7/28.
 */

public class ShopOrTimeQrConsumptionActivity extends BaseActivity implements SurfaceHolder.Callback, TimeItemInterface, ShopItemInterface, UpdateGoodsNumInterfaces {


    @BindView(R.id.preview_view)
    SurfaceView previewView;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.viewfinder_view)
    ViewfinderView viewfinderView;
    @BindView(R.id.id_listView)
    ListView idListView;
    private CaptureActivityHandler handler;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private String type;
    public static final String QR_SCAN_TYPE = "QR_SCAN_TYPE";

    public static void actionStart(Context context, String type) {
        Intent intent = new Intent(context, ShopOrTimeQrConsumptionActivity.class);
        intent.putExtra(QR_SCAN_TYPE, type);
        context.startActivity(intent);
    }

    private ShopAdapter shopAdapter;
    private ArrayList<SearchShopModel.DataBean.GoodsListBean> searchList = new ArrayList<>();
    private Map<String, ShopSkuInfoModel> selectedMaps;
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (handler != null) {
                handler.restartPreviewAndDecode();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr_shop_consumption);
        ButterKnife.bind(this);
        selectedMaps = BaseApplication.getSelectedMaps();
        CameraManager.init(mAc);
        type = getIntent().getStringExtra(QR_SCAN_TYPE);
        new TitleBuilder(mAc).setTitleText("扫码消费")
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightText("确定").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addShop();
            }
        });
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        initAdapter();
    }

    //商品加入购物车
    private void addShop() {
        for (int i = 0; i < searchList.size(); i++) {
            SearchShopModel.DataBean.GoodsListBean goodsListBean = searchList.get(i);
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(goodsListBean.getGoods_sku());
            if (shopSkuInfoModel == null) {
                shopSkuInfoModel = createSkuModel(goodsListBean.getStock(), goodsListBean.getGoods_type(), goodsListBean.getGoods_image(), goodsListBean.getBuy_num(), goodsListBean.getId(), goodsListBean.getGoods_sku(), goodsListBean.getGoods_name()
                        , goodsListBean.getGoods_shop_price(), goodsListBean.getGoods_category_parent_id());
                selectedMaps.put(goodsListBean.getGoods_sku(), shopSkuInfoModel);
            } else {
                shopSkuInfoModel.setBuy_num(goodsListBean.getBuy_num());
            }
        }
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        finish();
    }

    @Override
    public void refreshGoods() {
        shopAdapter.notifyDataSetChanged();
    }

    class ShopAdapter extends MultiItemTypeAdapter<SearchShopModel.DataBean.GoodsListBean> {
        public ShopAdapter(Context context, List<SearchShopModel.DataBean.GoodsListBean> datas) {
            super(context, datas);
            addItemViewDelegate(new TimeAdapterItem(ShopOrTimeQrConsumptionActivity.this));
            addItemViewDelegate(new ShopAdapterItem(ShopOrTimeQrConsumptionActivity.this));
        }
    }

    private void initAdapter() {
        shopAdapter = new ShopAdapter(mAc, searchList);
        idListView.setAdapter(shopAdapter);
    }


    @Override
    public void TimeConvert(ViewHolder viewHolder, final SearchShopModel.DataBean.GoodsListBean item, final int position) {
        ImageView mIdImg = viewHolder.getView(R.id.id_img);
        Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);
        viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
        viewHolder.setText(R.id.id_tv_price, item.getGoods_shop_price() + "");
        viewHolder.setText(R.id.id_tv_unit, "/" + item.getUnit());
        ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
        ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
        TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
        idTvAddNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateGoodsNumDialogForSearch dialog = new UpdateGoodsNumDialogForSearch(mAc, searchList.get(position), ShopOrTimeQrConsumptionActivity.this, "修改数量");
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }
        });
        if (item.getBuy_num() > 0) {
            idImgDel.setVisibility(View.VISIBLE);
            idTvAddNum.setText(Utils.MoneyQuZheng(item.getBuy_num() + ""));
            idTvAddNum.setVisibility(View.VISIBLE);
        } else {
            idImgDel.setVisibility(View.GONE);
            idTvAddNum.setText("0");
            idTvAddNum.setVisibility(View.GONE);
        }

        //增加
        idImgAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item.setBuy_num(item.getBuy_num() + 1);
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            }
        });


        //减少
        idImgDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getBuy_num() > 0) {
                    item.setBuy_num(item.getBuy_num() - 1);
                } else {
                    searchList.remove(position);
                }
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            }
        });
    }

    @Override
    public void ShopConvert(ViewHolder viewHolder, final SearchShopModel.DataBean.GoodsListBean item, final int position) {
        ImageView mIdImg = viewHolder.getView(R.id.id_img);
        Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);
        viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
        viewHolder.setText(R.id.id_tv_price, item.getGoods_shop_price());
        viewHolder.setText(R.id.id_tv_unit, "/" + item.getUnit());
        viewHolder.setText(R.id.id_tv_info, "库存：" + item.getStock());

        ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
        ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
        TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
        if (item.getBuy_num() > 0) {
            idImgDel.setVisibility(View.VISIBLE);
            idTvAddNum.setText(Utils.MoneyQuZheng(item.getBuy_num() + ""));
            idTvAddNum.setVisibility(View.VISIBLE);
        } else {
            idImgDel.setVisibility(View.GONE);
            idTvAddNum.setText("0");
            idTvAddNum.setVisibility(View.GONE);
        }
        idTvAddNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    UpdateGoodsNumDialogForSearch dialog = new UpdateGoodsNumDialogForSearch(mAc, searchList.get(position), ShopOrTimeQrConsumptionActivity.this, "修改数量");
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
            }
        });
        //增加
        idImgAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item.setBuy_num(item.getBuy_num() + 1);
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));

            }
        });

        //减少
        idImgDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getBuy_num() - 1 > 0) {
                    item.setBuy_num(item.getBuy_num() - 1);
                } else {
                    searchList.remove(position);
                }
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));

            }
        });
    }

    //创建商品model，用于全局记录
    private ShopSkuInfoModel createSkuModel(String stock, String type, String url, double buy_num, String id, String sku, String good_name, String shop_price, String goods_category_parent_id) {
        ShopSkuInfoModel shopSkuInfoModel = new ShopSkuInfoModel();
        shopSkuInfoModel.setBuy_num(buy_num);
        shopSkuInfoModel.setSku_id(id);
        shopSkuInfoModel.setSku(sku);
        shopSkuInfoModel.setSku_name(good_name);
        shopSkuInfoModel.setGoods_type(type);
        shopSkuInfoModel.setAdvUrl(url);
        shopSkuInfoModel.setShop_price(Float.parseFloat(shop_price));
        shopSkuInfoModel.setGoods_category_parent_id(goods_category_parent_id);
        shopSkuInfoModel.setSpec_str_md5("");
        if ("Putong".equals(type)) {
            shopSkuInfoModel.setMay_use_stock(Integer.parseInt(stock));
        } else {
            shopSkuInfoModel.setMay_use_stock(9999);
        }
        return shopSkuInfoModel;
    }

    @Override
    public void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;
        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }


    /**
     * Handler scan result
     *
     * @param result
     * @param barcode 获取结果
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        // FIXME
        if (resultString.equals("")) {
            showToast("扫描失败!");
            mhandler.sendMessageDelayed(new Message(), 3000);
        } else {
            initHttp(resultString);
        }

    }


    private void initHttp(String keyword) {
        HttpRequest.postUrl(Api.SEARCH_QR_SHOP)
                .addParams("keyword", keyword)
                .addParams("ScanGoodsType", type)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            SearchShopModel searchShopModel = gson.fromJson(json, SearchShopModel.class);
                            if (searchShopModel != null && searchShopModel.getData().getGoodsList().size() > 0) {
                                SearchShopModel.DataBean.GoodsListBean goodsListBean = searchShopModel.getData().getGoodsList().get(0);
                                int size = 0;
                                for (int i = 0; i < searchList.size(); i++) {
                                    SearchShopModel.DataBean.GoodsListBean goodsListBean1 = searchList.get(i);
                                    if (goodsListBean1.getId().equals(goodsListBean.getId())) {
                                        goodsListBean1.setBuy_num(goodsListBean1.getBuy_num() + 1);
                                        size = size + 1;
                                    }
                                }
                                if (size == 0) {
                                    ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(goodsListBean.getGoods_sku());
                                    if (shopSkuInfoModel != null) {
                                        goodsListBean.setBuy_num(shopSkuInfoModel.getBuy_num() + 1);
                                    } else {
                                        goodsListBean.setBuy_num(1);
                                    }
                                    searchList.add(goodsListBean);
                                }

                            } else {
                                showToast("商品不存在");
                            }
                        } else {
                            showToast("商品不存在");
                        }
                        shopAdapter.notifyDataSetChanged();
                        mhandler.sendMessageDelayed(new Message(), 3000);
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(R.string.http_error);
                        mhandler.sendMessageDelayed(new Message(), 3000);
                    }
                });
    }


    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(ShopOrTimeQrConsumptionActivity.this, decodeFormats,
                    characterSet);
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    public Handler getHandler() {
        return handler;
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
}
